﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ASBCC.Database.Entity;
using ASBCC.Database.Service;
using ASBCC.Workflow.K2Manager;
using ASBCC.Business;
using System.Data;

namespace BEGDC.CC.Web.Workflow.Admin
{
    public partial class FlowProcessConfigEdit : System.Web.UI.Page
    {
        #region Define
        private ProcessBusiness processBusiness = new ProcessBusiness();
        protected string ProcessName = string.Empty;
        /// <summary>
        /// 流程节点配置ID
        /// </summary>
        protected Guid ProcessConfigID
        {
            get
            {
                if (!string.IsNullOrEmpty(Request.QueryString["ProcessConfigID"]))
                    return new Guid(Request.QueryString["ProcessConfigID"]);
                else if (ViewState["ProcessConfigID"] != null)
                    return (Guid)ViewState["ProcessConfigID"];
                else
                    return Guid.Empty;
            }
        }

        protected string ProcName
        {
            get
            {
                return ViewState["ProcName"] == null ? string.Empty : ViewState["ProcName"].ToString();
            }
            set
            {
                ViewState["ProcName"] = value;
            }
        }

        private static readonly string[] ActionTypArr_MailTemplate = new string[] { K2ActionType.Submit, K2ActionType.Resubmit, K2ActionType.ReplyAskForMore, K2ActionType.Approve, K2ActionType.Reject, K2ActionType.Forward, K2ActionType.AskForMore, K2ActionType.Withdraw, K2ActionType.PostSubmit, K2ActionType.Validate, K2ActionType.Upload, K2ActionType.Acknowledge};

        #endregion

        #region Initialize
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindPage();
                InitMailTemplateDropdownLists();
                PopulateMailTemplateDropdownLists();
            }
        }

        protected override void OnInit(EventArgs e)
        {
            ddlAuditUserSource.Attributes.Add("onchange", "javascript:CutoverDisplay();");
            txtProcessName.Style["display"] = "none";
            base.OnInit(e);
        }
        #endregion

        #region event
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            #region ProcessConfig
            Flow_ProcessConfigTableEntity entity = Flow_ProcessConfigManager.SelectByKeys(ProcessConfigID);

            entity.Description = txtDescription.Text;
            entity.ShowStamp = chkShowStamp.Checked;
            entity.ActivityStampName = txtDefaultStamp.Text;

            entity.AuditUserSource = ddlAuditUserSource.SelectedValue;
            entity.AuditUsers = txtAuditUsers.Text.Trim();
            entity.AuditRole = txtAuditRole.Text.Trim();
            entity.ExcludeCurrentUser = (lstExcludeCurrentUser.SelectedIndex == 0);
            entity.SelectUserFromDialog = (lstSelectAuditUsers.SelectedIndex == 0);
            entity.ActionButtons = string.Empty;
            entity.EnableBatchAction = lstEnableBatchApprove.SelectedIndex == 0;
            entity.AuditRule = lstAuditRule.SelectedValue;

            foreach (ListItem item in lstAuditorActions.Items)
            {
                if (item.Selected)
                    entity.ActionButtons += ";" + item.Value;
            }
            entity.ActionButtons = entity.ActionButtons.TrimStart(';');
            int dutyDays;
            if (int.TryParse(txtDutyDays.Text, out dutyDays))
                entity.DutyDays = dutyDays;
            else
                entity.DutyDays = 0;

            Flow_ProcessConfigManager.Update(entity);

            #endregion

            #region ProcessMailConfig
            foreach (string actionType in ActionTypArr_MailTemplate)
            {
                DropDownList ddlApplicant = (DropDownList)FindControl(string.Format("ddlMTemp_{0}_Notify_Applicant", actionType));
                DropDownList ddlApprover = (DropDownList)FindControl(string.Format("ddlMTemp_{0}_Notify_Approver", actionType));

                Flow_ProcessMailConfigTableEntitySet mailConfigSet = Flow_ProcessMailConfigManager.SelectByCondition(string.Format("ProcName='{0}' and ActivityName='{1}' and ActionType='{2}'", entity.ProcName, entity.ActivityName, actionType));
                Flow_ProcessMailConfigTableEntity mailConfig = null;
                if (mailConfigSet == null || mailConfigSet.Tables.Count == 0 || mailConfigSet.Tables[0].Rows.Count == 0)
                {
                    mailConfig = new Flow_ProcessMailConfigTableEntity();
                    mailConfig.ProcessMailConfigID = Guid.NewGuid();
                    mailConfig.ActionType = actionType;
                    mailConfig.ActivityName = entity.ActivityName;
                    mailConfig.ProcName = entity.ProcName;
                    mailConfig.ToApplicantTemplate = int.Parse(ddlApplicant.SelectedValue);
                    mailConfig.ToAuditorTemplate = int.Parse(ddlApprover.SelectedValue);
                    Flow_ProcessMailConfigManager.Insert(mailConfig);
                }
                else
                {
                    mailConfig = mailConfigSet[0];
                    mailConfig.ActionType = actionType;
                    mailConfig.ActivityName = entity.ActivityName;
                    mailConfig.ProcName = entity.ProcName;
                    mailConfig.ToApplicantTemplate = int.Parse(ddlApplicant.SelectedValue);
                    mailConfig.ToAuditorTemplate = int.Parse(ddlApprover.SelectedValue);
                    Flow_ProcessMailConfigManager.Update(mailConfig);
                }
            }
            #endregion

            this.ClientScript.RegisterClientScriptBlock(this.GetType(), "Alert", string.Format("alert('{0}');window.close();window.returnValue='reload';", "SaveSuccessfully"), true);

            //Page.RegisterClientScriptBlock("", "<script>VBAlert('" + BEGDC.CC.Resource.SystemMessage.CR001 + "');window.close();window.returnValue='reload';</script>");
        }

        /// <summary>
        /// 返回列表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnGoBack_Click(object sender, EventArgs e)
        {
            Response.Redirect(string.Format("FlowProcessConfigManagement.aspx?ProcName={0}", this.ProcName));
        }
        #endregion

        #region Function

        private void InitMailTemplateDropdownLists()
        {
            MailTemplateTableEntitySet mailTemplates = MailTemplateManager.SelectByCondition("TemplateCode like 'Flow_%'");
            DataTable tbMailTemplate = mailTemplates.Tables[0];
            DataRow newRow = tbMailTemplate.NewRow();
            newRow["TemplateID"] = -1;
            newRow["TemplateCode"] = string.Empty;
            tbMailTemplate.Rows.InsertAt(newRow, 0);
            tbMailTemplate.AcceptChanges();

            for (int i = 0; i < ActionTypArr_MailTemplate.Length; i++)
            {
                string actionType = ActionTypArr_MailTemplate[i];
                DropDownList ddlApplicant = (DropDownList)FindControl(string.Format("ddlMTemp_{0}_Notify_Applicant", actionType));
                DropDownList ddlApprover = (DropDownList)FindControl(string.Format("ddlMTemp_{0}_Notify_Approver", actionType));

                ddlApplicant.DataSource = tbMailTemplate.Copy();
                ddlApplicant.DataTextField = "TemplateCode";
                ddlApplicant.DataValueField = "TemplateID";
                ddlApplicant.DataBind();
                ddlApplicant.SelectedValue = "-1";

                ddlApprover.DataSource = tbMailTemplate.Copy();
                ddlApprover.DataTextField = "TemplateCode";
                ddlApprover.DataValueField = "TemplateID";
                ddlApprover.DataBind();
                ddlApprover.SelectedValue = "-1";
            }
        }

        private void PopulateMailTemplateDropdownLists()
        {
            Flow_ProcessMailConfigTableEntitySet mailConfigSet = Flow_ProcessMailConfigManager.SelectByCondition(string.Format("ProcName='{0}' and ActivityName='{1}'", txtProcessName.Text, txtActivityName.Text));
            if (mailConfigSet != null && mailConfigSet.Tables.Count > 0)
            {
                DataTable mailConfig = mailConfigSet.Tables[0];

                for (int i = 0; i < ActionTypArr_MailTemplate.Length; i++)
                {
                    string actionType = ActionTypArr_MailTemplate[i];
                    DropDownList ddlApplicant = (DropDownList)FindControl(string.Format("ddlMTemp_{0}_Notify_Applicant", actionType));
                    DropDownList ddlApprover = (DropDownList)FindControl(string.Format("ddlMTemp_{0}_Notify_Approver", actionType));

                    DataRow[] rows = mailConfig.Select(string.Format("ActionType='{0}'", actionType));
                    if (rows != null && rows.Length > 0)
                    {
                        object objToApplicantTemplate = rows[0]["ToApplicantTemplate"];
                        object objToAuditorTemplate = rows[0]["ToAuditorTemplate"];

                        if (objToApplicantTemplate != null && objToApplicantTemplate != DBNull.Value && (int)objToApplicantTemplate > -1)
                        {
                            ddlApplicant.SelectedValue = objToApplicantTemplate.ToString();
                        }

                        if (objToAuditorTemplate != null && objToAuditorTemplate != DBNull.Value && (int)objToAuditorTemplate > -1)
                        {
                            ddlApprover.SelectedValue = objToAuditorTemplate.ToString();
                        }
                    }
                }
            }
        }
        /// <summary>
        /// 绑定页面
        /// </summary>
        private void BindPage()
        {
            //如果流程步骤ID为空，则返回
            if (this.ProcessConfigID == Guid.Empty)
                return;
            #region ProcessConfig
            Flow_ProcessConfigTableEntity entity = processBusiness.GetProcessConfigEntityByKey(ProcessConfigID);

            //根据流程步骤ID获得步骤实体为空，则返回
            if (entity == null)
                return;

            Flow_ProcessTableEntitySet procSet = Flow_ProcessManager.SelectByCondition(string.Format("ProcName='{0}'", entity.ProcName));
            Flow_ProcessTableEntity proc = procSet[0];

            txtProcessName.Text = entity.ProcName;
            txtProcessNameFull.Text = proc.ProcDisplayEn;
            txtActivityName.Text = entity.ActivityName;
            ProcName = entity.ProcName;

            txtDescription.Text = entity.Description;
            chkShowStamp.Checked = entity.ShowStamp == true;
            txtDefaultStamp.Text = entity.ActivityStampName;

            txtAuditUsers.Text = entity.AuditUsers;
            txtAuditRole.Text = entity.AuditRole;
            lstExcludeCurrentUser.SelectedIndex = entity.ExcludeCurrentUser == true ? 0 : 1;

            if (!string.IsNullOrEmpty(entity.AuditUserSource))
            {
                ddlAuditUserSource.SelectedValue = entity.AuditUserSource;
            }
            else
            {
                ddlAuditUserSource.SelectedIndex = 0;
            }

            lstSelectAuditUsers.SelectedIndex = (entity.SelectUserFromDialog == true ? 0 : 1);
            lstEnableBatchApprove.SelectedIndex = (entity.EnableBatchAction == true ? 0 : 1);
            lstAuditRule.SelectedValue = entity.AuditRule;
            if (!string.IsNullOrEmpty(entity.ActionButtons))
            {
                System.Collections.Generic.List<string> list = new System.Collections.Generic.List<string>();
                list.AddRange(entity.ActionButtons.Split(';'));
                foreach (ListItem item in lstAuditorActions.Items)
                {
                    if (list.Contains(item.Value))
                        item.Selected = true;
                }
            }
            txtDutyDays.Text = entity.DutyDays.ToString();

            #endregion

        }

        /// <summary>
        /// 根据actionType提取邮件配置实体
        /// </summary>
        /// <param name="es"></param>
        /// <param name="actionType"></param>
        /// <returns></returns>
        private Flow_ProcessMailConfigTableEntity GetMailConfigEntity(Flow_ProcessMailConfigTableEntitySet es, string actionType)
        {
            return (Flow_ProcessMailConfigTableEntity)es.GetEntity(0, string.Format("ActionType='{0}'", actionType));
        }
        #endregion
    }
}
